package cn.ctyun.ipush.web.interceptor;

import cn.ctyun.ipush.web.user.bo.UserModel;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2015/5/21.
 */
public class DispatcherInterceptor implements HandlerInterceptor {
    private final Logger log = Logger.getLogger(LoginInterceptor.class);
    public String[] allowUrls;//还没发现可以直接配置不拦截的资源，所以在代码里面来排除
    public String mappingURL;
    public String redirectURL;

    public void setRedirectURL(String redirectURL) {
        this.redirectURL = redirectURL;
    }

    public void setMappingURL(String mappingURL) {
        this.mappingURL = mappingURL;
    }

    public void setAllowUrls(String[] allowUrls) {
        this.allowUrls = allowUrls;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        boolean flag = false;
        UserModel userModel =null;
        for(String allow:allowUrls){
            if(url.contains(allow)){
                return  true;
            }
        }
        if(url!=null){
            if(url.toLowerCase().indexOf(mappingURL)>-1)   {  //mappping 代表 /api

                flag = true;
            }else{
                flag = false;
            }
        }
        if(!flag){
            log.info("====url===="+url+"===== is not api");
            request.getRequestDispatcher(redirectURL).forward(request,response); //redirectURL  代表 /pages/index.jsp  主页
            return false;
        }else{
            log.info("====url===="+url+"===== is api");
            return true;
        }//To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
